/*
 * M2Client.java
 * 
 *  author: Daniel Rudigier
 *    date: 25.12.2008
 * 
 * 
 */
package at.momberban2.me.game;

import at.syncme.framework.Algorithm;
import at.syncme.framework.Event;
import at.syncme.framework.EventHandler;

/**
 * handle events if game is configured as client side
 * 
 * @author Daniel Rudigier
 */
public class M2Client implements EventHandler {
    private M2Game game;

    private M2GameState m2state;

    private Algorithm algo;

    /**
     * constructor
     * 
     * @param game
     */
    public M2Client(M2Game game) {
        this.game = game;
        this.m2state = game.m2state;
        this.algo = game.getAlgo();
    }

    /**
     * override
     * 
     * @see at.syncme.framework.EventHandler#gameEvent(at.syncme.framework.Event)
     */
    public void gameEvent(Event e) {
        if (e.isAcknowledged()) { // received from the server
            fromServer(e);
        } else if (e.isLocal()) {
            algo.sendEvent(e);
            System.out.println("local event to be transferred");
        } else {
            System.out.println("received a NACK!! " + e.getId() + ":"
                    + e.getMessage());
        }
    }

    /**
     * received an event from the server
     * 
     * @param e
     */
    private void fromServer(Event e) {
        if (e.getId() == Event.PLAYER_CHALLANGE) {
            // challenge successful, assign my received id
            Byte id = (Byte) e.getMessage();
            game.setMe(id);

            // request current game state
            System.out.println("i am player " + id + ", requsting game state");
            algo.sendEvent(Event.create(Event.GAME_STATE, Event.PRIORITY_HIGH));
        } else if (e.getId() == Event.GAME_STATE) {
            game.setGs((M2GameState) e.getMessage());
            System.out.println("game state received.");
        } else {
            System.out.println("client doesn't understand my friend");
        }
    }

    /**
     * override
     * 
     * @see at.syncme.framework.EventHandler#setupEvent(at.syncme.framework.Event)
     */
    public void setupEvent(Event arg0) {
        // nop
    }

}
